// 主要用于清除cmake生成的各种cache文件

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>

void delete_directory(const char *path);

int main() {
    const char *dirname = "./CMakeFiles"; // 要删除的目录路径
    delete_directory(dirname);

    const char *filename = "CMakeCache.txt"; // 要删除的文件名
    if (remove(filename) != 0) {
        perror("Error deleting file");
        return -1;
    } else {
        printf("%s deleted successfully.\n", filename);
    }

    filename = "cmake_install.cmake"; // 要删除的文件名
    if (remove(filename) != 0) {
        perror("Error deleting file");
        return -1;
    } else {
        printf("%s deleted successfully.\n", filename);
    }

    filename = "Makefile"; // 要删除的文件名
    if (remove(filename) != 0) {
        perror("Error deleting file");
        return -1;
    } else {
        printf("%s deleted successfully.\n", filename);
    }

    return 0;
}

void delete_directory(const char *path) {
    DIR *d = opendir(path);
    if (!d) {
        perror("opendir failed");
        return;
    }

    struct dirent *p;
    while ((p = readdir(d))) {
        struct stat st;
        char subpath[256+16]; // 假设路径长度不会超过256字符

        // 忽略 "." 和 ".."
        if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, "..")) {
            continue;
        }

        snprintf(subpath, sizeof(subpath), "%s/%s", path, p->d_name);
        if (stat(subpath, &st)) {
            perror("stat failed");
            continue;
        }

        if (S_ISDIR(st.st_mode)) {
            // 如果是目录，递归调用 delete_directory
            delete_directory(subpath);
        } else {
            // 如果是文件，直接删除
            if (remove(subpath) != 0) {
                perror("remove failed");
            } else {
                printf("%s deleted successfully.\n", subpath);
            }
        }
    }
    closedir(d);

    // 删除空目录本身
    if (rmdir(path) != 0) {
        perror("rmdir failed");
    } else {
        printf("%s directory deleted successfully.\n", path);
    }
}